<template>
  <div ref="content">
    <a-card :bordered="false">
      <a-page-header
        style="border-bottom: 1px solid rgb(235, 237, 240); padding: 8px 16px"
        title=""
      />
      <split splitHeight="100%" leftWidth="220">
        <template slot="paneL">
          <!-- 部门树 -->
          <dept-tree
            ref="deptTree"
            :deptOptions="deptOptions"
            :defalutExpandedKeys="expandedKeys"
            @setDataOptionInfo="setDataOptionInfo"
            @select="clickDeptNode"
          />
        </template>
        <template slot="paneR">
          <!-- 条件搜索 -->
          <div class="table-page-search-wrapper">
            <a-form :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-row :gutter="48">
                <a-col :md="6" :sm="24">
                  <a-form-item label="姓名">
                    <a-input
                      v-model="queryParam.name"
                      placeholder="请输入姓名"
                      allow-clear
                      @keyup.enter.native="handleQuery"
                    />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="登录名">
                    <a-input
                      v-model="queryParam.userName"
                      placeholder="请输入登录名"
                      allow-clear
                      @keyup.enter.native="handleQuery"
                    />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="手机号">
                    <a-input
                      v-model="queryParam.phonenumber"
                      placeholder="请输入手机号"
                      allow-clear
                      @keyup.enter.native="handleQuery"
                    />
                  </a-form-item>
                </a-col>

                <a-col :md="6" :sm="24">
                  <a-form-item label="公司名称">
                    <a-select
                      placeholder="请选择公司"
                      v-model="queryParam.companyId"
                      style="width: 100%"
                      allow-clear
                      option-filter-prop="children"
                      :filter-option="filterOption"
                      show-search
                    >
                      <a-select-option
                        v-for="(d, index) in companyList"
                        :key="index"
                        :value="d.id"
                        >{{ d.companyName }}</a-select-option
                      >
                    </a-select>
                  </a-form-item> </a-col
                ><a-col :md="6" :sm="24" v-if="advanced">
                  <a-form-item label="业务城市">
                    <a-input
                      v-model="queryParam.city"
                      placeholder="请输入业务城市"
                      allow-clear
                      @keyup.enter.native="handleQuery"
                    />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24" v-if="advanced">
                  <a-form-item label="业务类型">
                    <a-select
                      placeholder="请选择业务类型"
                      v-model="queryParam.customerType"
                      style="width: 100%"
                      allow-clear
                      option-filter-prop="children"
                    >
                      <a-select-option
                        v-for="(d, index) in customerTypeOptions"
                        :key="index"
                        :value="d.dictValue"
                        >{{ d.dictLabel }}</a-select-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24" v-if="advanced">
                  <a-form-item label="创建时间">
                    <a-range-picker
                      style="width: 100%"
                      v-model="dateRange"
                      valueFormat="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col>
                  <span
                    class="table-page-search-submitButtons"
                    style="float: right"
                  >
                    <a-button type="primary" @click="handleQuery"
                      ><a-icon type="search" />查询</a-button
                    >
                    <a-button style="margin-left: 8px" @click="resetQuery"
                      ><a-icon type="redo" />重置</a-button
                    >
                    <a @click="toggleAdvanced" style="margin-left: 8px">
                      {{ advanced ? "收起" : "展开" }}
                      <a-icon :type="advanced ? 'up' : 'down'" />
                    </a>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-divider />
          <!-- 增加修改 -->
          <sys-user-add-form
            v-if="showAddModal"
            ref="sysUserAddForm"
            :statusOptions="statusOptions"
            :sexOptions="sexOptions"
            :userTypeOptions="userTypeOptions"
            :defalutExpandedKeys="expandedKeys"
            :deptCheckedValue="deptCheckedValue"
            :customerTypeOptions="customerTypeOptions"
            :companyList="companyList"
            :busTypeOptions="busTypeOptions"
            @ok="getList"
            @close="showAddModal = false"
          />
          <!-- 编辑用户,单独封装了组件 -->
          <sys-user-edit-form
            v-if="showEditModal"
            ref="sysUserEditForm"
            :statusOptions="statusOptions"
            :sexOptions="sexOptions"
            :userTypeOptions="userTypeOptions"
            :defalutExpandedKeys="expandedKeys"
            :customerTypeOptions="customerTypeOptions"
            :companyList="companyList"
            :busTypeOptions="busTypeOptions"
            @ok="getList"
            @close="showEditModal = false"
          />
          <!-- 修改密码抽屉 -->
          <reset-password
            v-if="showResetPassword"
            ref="resetPassword"
            @close="showResetPassword = false"
          />
          <!-- 上传文件 -->
          <import-excel
            title="导入用户"
            upload-msg="是否更新已经存在的用户数据"
            upload-action="/system/user/importData"
            ref="importExcel"
            @ok="getList"
            @importTemplate="importTemplate"
          />
          <advance-table
            :columns="columns"
            :data-source="list"
            :title="tableTitle"
            :loading="loading"
            rowKey="id"
            size="middle"
            tableKey="system-user-SysUserIndex-table"
            @change="handleTableChange"
            @refresh="getList"
            :format-conditions="true"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
            :pagination="{
              current: queryParam.pageNum,
              pageSize: queryParam.pageSize,
              total: total,
              showSizeChanger: true,
              showLessItems: true,
              showQuickJumper: true,
              showTotal: (total, range) =>
                `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
              onChange: changeSize,
              onShowSizeChange: onShowSizeChange,
            }"
            :scroll="{ x: '100%' }"
          >
            <div class="table-operations" slot="button">
              <a-button
                type="primary"
                @click="handleAdd()"
                v-hasPermi="['system:user:add']"
              >
                <a-icon type="plus" />新增
              </a-button>

              <a-button
                type="danger"
                v-if="!multiple"
                @click="handleDelete"
                v-hasPermi="['system:user:remove']"
              >
                <a-icon type="delete" />删除
              </a-button>
              <a-button
                type=""
                @click="$refs.importExcel.importExcelHandleOpen()"
                v-hasPermi="['system:user:import']"
              >
                <a-icon type="import" />导入
              </a-button>
              <a-button
                type=""
                @click="handleExport"
                v-hasPermi="['system:user:export']"
              >
                <a-icon type="download" />导出
              </a-button>
            </div>
            <span slot="status" slot-scope="{ record }">
              <a-badge
                :status="record.status == '0' ? 'processing' : 'error'"
                :text="statusFormat(record)"
              />
            </span>
            <span slot="customerType" slot-scope="{ record }">
              <span
                v-for="(item, i) in JSON.parse(record.customerType)"
                :key="i"
                >{{ customerTypeFormat(item) }},</span
              >
            </span>
            <span slot="companyId" slot-scope="{ text }">
              <a-tooltip placement="bottom">
                <template slot="title">
                  {{ companyFormat(companyList, text) }}
                </template>
                {{ companyFormat(companyList, text) }}
              </a-tooltip>
            </span>
            <span slot="companyBalance" slot-scope="{ text }">
              <a-tooltip placement="bottom">
                <template slot="title">
                  <a style="font-size: 14px; color: #87d068; font-weight: 500">
                    ¥
                    {{
                      parseFloat(
                        companyBalanceFormat(companyList, text)
                      ).toFixed(2)
                    }}
                  </a>
                </template>
                <a style="font-size: 14px; color: #87d068; font-weight: 500">
                  ¥
                  {{
                    parseFloat(companyBalanceFormat(companyList, text)).toFixed(
                      2
                    )
                  }}</a
                >
              </a-tooltip>
            </span>
            <span slot="name" slot-scope="{ text, record, index }">
              <a @click="onClickRow(record, index)">
                <a-avatar
                  :style="{ backgroundColor: getRandomColor(index) }"
                  style="color: #fff"
                >
                  {{ getShowName(text) }}
                </a-avatar>
                {{ text }}
              </a>
            </span>
            <span slot="createTime" slot-scope="text, record">
              {{ parseTime(record.createTime) }}
            </span>
            <span slot="money" slot-scope="{ text }">
              ¥&nbsp; {{ parseFloat(text ? text : 0).toFixed(2) }}
            </span>

            <span slot="busType" slot-scope="{ record }">
              {{ busTypeFormat(record) }}
            </span>
            <span slot="operation" slot-scope="{ record }">
              <a
                @click="handleUpdate(record, undefined)"
                v-hasPermi="['system:user:edit']"
              >
                修改
              </a>
              <a-divider
                type="vertical"
                v-if="record.id !== 1"
                v-hasPermi="['system:user:remove']"
              />
              <a
                @click="handleDelete(record)"
                v-if="record.id !== 1"
                v-hasPermi="['system:user:remove']"
              >
                删除
              </a>
              <a-divider
                type="vertical"
                v-hasPermi="['system:user:resetPwd']"
              />
              <a
                @click="handleResetPwd(record)"
                v-hasPermi="['system:user:resetPwd']"
              >
                重置密码
              </a>
            </span>
          </advance-table>
        </template>
      </split>
    </a-card>
  </div>
</template>

<script>
import {
  listUser,
  delUser,
  exportUser,
  importTemplate,
  findListUserBycompanyId,
} from "@/api/system/user";

import { listDeptTree } from "@/api/system/dept";
import ResetPassword from "./modules/ResetPassword";
import SysUserAddForm from "./modules/SysUserAddForm";
import SysUserEditForm from "./modules/SysUserEditForm";
import ImportExcel from "@/components/pt/import/ImportExcel";
import DeptTree from "./modules/DeptTree";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import Split from "@/components/pt/split/Index";
export default {
  name: "User",
  components: {
    ResetPassword,
    SysUserEditForm,
    ImportExcel,
    AdvanceTable,
    SysUserAddForm,
    Split,
    DeptTree,
  },
  data() {
    return {
      visible: false,
      zyUserId: "",
      zyUserList: [],
      consultUserId: "",
      zyvisible: false,
      genjinuser: 0,
      confirmLoading: false,
      showAddModal: false,
      showEditModal: false,
      showResetPassword: false,
      list: [],
      colorList: ["#F38709", "#813AFD", "#00C4AA", "#4B7AEE"],
      tableTitle: "用户管理",
      selectedRowKeys: [],
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      ids: [],
      userNames: [],
      expandedKeys: [],
      loading: false,
      total: 0,
      // 状态数据字典
      statusOptions: [],
      sexOptions: [],
      userTypeOptions: [],
      deptCheckedValue: {},
      // 部门树选项
      deptOptions: [],
      // 客户类型字典
      customerTypeOptions: [],
      // 公司信息
      companyList: [],
      // 业务类型
      busTypeOptions: [],
      // 日期范围
      dateRange: [],
      // treeData

      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      columns: [
        {
          title: "姓名",
          dataIndex: "name",
          width: "120px",
          scopedSlots: { customRender: "name" },
        },
        {
          title: "公司",
          dataIndex: "companyId",
          ellipsis: true,
          width: "180px",
          scopedSlots: { customRender: "companyId" },
        },
        {
          title: "余额",
          dataIndex: "companyId",
          ellipsis: true,
          width: "120px",
          scopedSlots: { customRender: "companyBalance" },
          align: "right",
        },
        {
          title: "登录名",
          dataIndex: "userName",
          align: "center",
          width: "120px",
        },
        {
          title: "电话",
          dataIndex: "phonenumber",
          align: "center",
          width: "120px",
        },
        {
          title: "业务城市",
          dataIndex: "city",
          align: "center",
          ellipsis: true,
          width: "140px",
        },
        {
          title: "业务类型",
          dataIndex: "customerType",
          scopedSlots: { customRender: "customerType" },
          align: "center",
          width: "80px",
        },
        {
          title: "日分配人数",
          dataIndex: "dayCount",
          align: "right",
          width: "90px",
        },
        {
          title: "已分配人数",
          dataIndex: "dayShareCount",
          align: "right",
          width: "90px",
        },
        {
          title: "次费用",
          dataIndex: "money",
          align: "right",
          scopedSlots: { customRender: "money" },
          width: "90px",
        },

        {
          title: "用户类型",
          width: "90px",
          scopedSlots: { customRender: "busType" },
          dataIndex: "busType",
          align: "center",
        },
        {
          title: "创建时间",
          ellipsis: true,
          sorter: true,
          width: "180px",
          dataIndex: "createTime",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "operation",
          width: "200px",
          scopedSlots: { customRender: "operation" },
          fixed: "right",
        },
      ],
    };
  },
  filters: {},
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("sys_user_type").then((response) => {
      this.userTypeOptions = response.data;
    });
    this.getDicts("customer_type").then((response) => {
      this.customerTypeOptions = response.data;
    });
    this.getDicts("bus_type").then((response) => {
      this.busTypeOptions = response.data;
    });
    this.getCompanyInfos({}).then((res) => {
      this.companyList = res.data;
    });
  },
  computed: {},
  watch: {},
  methods: {
    findListUserBycompanyId() {
      findListUserBycompanyId().then((res) => {
        this.zyUserList = res.data;
      });
    },
    showModalzy() {
      this.findListUserBycompanyId();
      this.zyvisible = true;
      this.genjinuser = 0;
    },
    showModalzyConsult() {
      this.findListUserBycompanyId();
      this.zyvisible = true;
      this.genjinuser = 1;
    },
    handleOk(e) {
      this.confirmLoading = true;
      setTimeout(() => {
        this.zyvisible = false;
        this.confirmLoading = false;
        const userIds = this.ids;
        if (userIds.length > 1) {
          this.$error({
            title: "错误提示！",
            content: "只能选择一条数据！",
          });
          return;
        }
      }, 2000);
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.zyvisible = false;
    },
    // 公司筛选
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    importTemplate(expanded, record) {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listDeptTree("0", 3).then((response) => {
        this.deptOptions = response.data;
        this.getExpandedKeys(this.deptOptions, 3);
      });
    },
    getExpandedKeys(nodes, expandLevel) {
      if (expandLevel > 1) {
        // 最后一层不展开
        if (nodes != null) {
          nodes.forEach((node) => {
            this.expandedKeys.push(node.id);
            expandLevel = expandLevel - 1;
            return this.getExpandedKeys(node.children, expandLevel);
          });
        }
      }
    },
    // 客户类型字典翻译
    customerTypeFormat(customerType) {
      if (customerType) {
        return this.selectDictLabel(this.customerTypeOptions, customerType);
      } else {
        return "";
      }
    }, // 客户类型字典翻译
    busTypeFormat(row) {
      if (row.busType) {
        return this.selectDictLabel(this.busTypeOptions, row.busType);
      } else {
        return "";
      }
    },
    companyFormat(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].id === "" + value) {
          actions.push(datas[key].companyName);
          return true;
        }
      });
      return actions.join("");
    },
    companyBalanceFormat(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].id === "" + value) {
          actions.push(datas[key].balance);
          return true;
        }
      });
      return actions.join("");
    },
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.shareStatus);
    },
    userTypeFormat(row) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    /** 查询定时任务列表 */
    getList() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.loading = true;
      listUser(this.addDateRange(this.queryParam, this.dateRange)).then(
        (response) => {
          this.list = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      };
      this.handleQuery();
    },
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.userNames = this.selectedRows.map((item) => item.name);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    clickDeptNode(node) {
      this.queryParam.deptId = node.$options.propsData.eventKey;
      this.deptCheckedValue.ids = node.$options.propsData.eventKey;
      this.tableTitle = node.$options.propsData.label;
      if (node.$options.propsData.dataRef.attributes.deptType === "dept") {
        this.deptCheckedValue = {
          ids: node.$options.propsData.eventKey,
          names: node.$options.propsData.label,
        };
      } else {
        this.deptCheckedValue = {};
      }
      console.log(this.deptCheckedValue);
      this.getList();
    },
    handleAdd() {
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.sysUserAddForm.handleAdd());
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.sysUserEditForm.handleUpdate(record, ids)
      );
    },
    handleResetPwd(record) {
      this.showResetPassword = true;
      this.$nextTick(() => this.$refs.resetPassword.handleResetPwd(record));
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const userIds = row.id || this.ids;
      const userNames = row.name || this.userNames;
      this.$confirm({
        title: "确认删除所选中数据?",
        content: "当前选中编号为" + userNames + "的数据",
        onOk() {
          return delUser(userIds).then(() => {
            that.onSelectChange([], []);
            that.getList();
            that.$message.success("删除成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportUser(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
    getRandomColor(index) {
      // const randomValue = Math.round(Math.random() * 3)
      return this.colorList[index % 4];
    },
    getShowName(name) {
      if (name.length > 2) {
        name = name.substring(name.length - 2);
      }
      return name;
    },
    onClickRow(record, index) {
      this.handleUpdate(record, "");
    },
    setDataOptionInfo(treeDataOption) {
      this.deptOptions = treeDataOption;
    },
    handleTableChange(pagination, filters, sorter) {
      if (
        sorter.field !== undefined &&
        sorter.field !== null &&
        sorter.field !== ""
      ) {
        this.queryParam.orderByColumn = "t." + sorter.field;
        this.queryParam.isAsc = sorter.order;
      }
      this.getList();
    },
  },
};
</script>
<style lang="less" scoped>
.ant-divider-horizontal {
  margin: 0;
  background: rgb(235, 237, 240);
}
.demo-split {
  height: 200px;
}
.demo-split-pane {
  padding: 10px;
}
.ant-avatar {
  font-size: 12px;
  border-radius: 4px;
  vertical-align: middle;
  margin-right: 8px;
}

/deep/.ant-table-body {
  min-height: calc(100vh - 340px);
}
/deep/.ant-table-placeholder {
  // 将暂无数据提示隐藏，否则没有数据时将表格高度制定导致暂无数据挤到最底下
  display: none;
}
</style>
